/*
Source : https://leetcode.com/problems/remove-nth-node-from-end-of-list/
Author : nflush@outlook.com
Date   : 2016-08-23
*/

/*
19. Remove Nth Node From End of List

    Total Accepted: 125512
    Total Submissions: 407737
    Difficulty: Easy

Given a linked list, remove the nth node from the end of list and return its head.

For example,

   Given linked list: 1->2->3->4->5, and n = 2.

   After removing the second node from the end, the linked list becomes 1->2->3->5.

Note:
Given n will always be valid.
Try to do this in one pass.

Subscribe to see which companies asked this question
*/

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution { // 4ms
public:
    ListNode* removeNthFromEnd(ListNode* head, int n) {
        ListNode *cur = head;
        ListNode node(0);
        ListNode *pre = &node;
        node.next = head;
        while(n--){
            cur = cur->next;
        }
        for(;cur;cur=cur->next){
            pre = pre->next;
        }
        pre->next = pre->next->next;
        return node.next;
    }
};

class Solution { // 4ms
public:
    ListNode* removeNthFromEnd(ListNode* head, int n) {
        ListNode *cur = head;
        ListNode *pre = head;
        while(n--){
            cur = cur->next;
        }
        if (cur){
            for(;cur->next;cur=cur->next){
                pre = pre->next;
            }
            pre->next = pre->next->next;
            return head;
        } else {
            return head->next;
        }
    }
};

